﻿using KseCms.Application.Services;
using KseCms.Core;
using Microsoft.EntityFrameworkCore;
using System;

namespace KseCms.Application
{
    public class OrderService : IOrderService, ITransient
    {
        private readonly IRepository<Order> _orderRepository;

        private readonly IRepository<Product> _productRepository;


        public OrderService(IRepository<Order> OrderRepository,
            IRepository<Product> productRepository)
        {
            _orderRepository = OrderRepository;
            _productRepository = productRepository;
        }

        public async Task<OrderDto> GetById(string id)
        {
            var entity = await _orderRepository.DetachedEntities.FirstOrDefaultAsync(n => n.Id == id);

            return entity.Adapt<OrderDto>();
        }

        public async Task<PagedList<OrderDto>> GetList(PageDto page)
        {

            var query = from order in _orderRepository.AsQueryable(false)
                        join product in _productRepository.AsQueryable(false) on order.ProductId equals product.Id
                        select new OrderDto
                        {
                            Id = order.Id,
                            Quantity = order.Quantity,
                            Amount = order.Amount,
                            CreatedDate = order.CreatedDate,
                            UpdatedDate = order.UpdatedDate,
                            Product = product.Adapt<ProductDto>(),
                        };

            return await query.ToPagedListAsync(page.PageIndex,page.PageSize);
        }

        public async Task Create(OrderDto order)
        {
            var entity = order.Adapt<Order>();

            await _orderRepository.InsertNowAsync(entity);
        }

        public async Task Delete(string id)
        {
            if (!IsExists(id))
                throw Oops.Oh(ErrorCodes.record_not_exist);

            await _orderRepository.DeleteNowAsync(id);
        }

        public async Task Update(OrderDto order)
        {
            UpdateValidation(order);

            var entity = order.Adapt<Order>();

            await _orderRepository.UpdateNowAsync(entity);
        }

        private void UpdateValidation(OrderDto order)
        {
            if (!IsExists(order.Id))
                throw Oops.Oh(ErrorCodes.record_not_exist);

            //to-do other validate
        }

        private bool IsExists(string id)
        {
            return _orderRepository.DetachedEntities.Any(u => u.Id == id);
        }
    }
}